#!/use/bin/python
# coding=utf-8
# 将  大数据统计的数据 保存到数据库中
import datetime
import pymysql
import requests
import json

from dbutils.pooled_db import PooledDB

# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.150.109', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# 调用大数据接口 获取节点请求次数
def getNodeNum(date):
    url = "http://192.168.2.176:8080/star-rocks/api/v1/query-service?token=37f749e518af436bbebbe5ad"
    # url = "https://api-bdata.skysrt.com/star-rocks/api/v1/query-service?token=37f749e518af436bbebbe5ad"

    payload = json.dumps({
        "modelId": "lifeAssistantNodeConversion",
        "requireParams": {
            "day": f"{date}"
        }
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    #print(response.text)
    dataJson = json.loads(response.text)
    conn, cur = getConfConnection()
    delsql = f" delete from inter_actify_r_node_number where ref_date= '{date}' "
    cur.execute(delsql)
    conn.commit()
    rowsInt = 0
    for item in dataJson["data"]:
        rowsInt = rowsInt + 1
        sql = "INSERT INTO inter_actify_r_node_number (uv, pv, ref_date, node_id) VALUES (%s, %s, %s, %s)"
        values = (item["uv"], item["pv"], item["day"], item["node_id"])
        cur.execute(sql, values)
    conn.commit()
    logDetail = f"{date}日-保存节点曝光次数,新增的节点数为{rowsInt}"
    print(logDetail)

# 调用大数据接口 获取按钮请求次数
def getButtonNum(date):
    url = "http://192.168.2.176:8080/star-rocks/api/v1/query-service?token=37f749e518af436bbebbe5ad"
    # url = "https://api-bdata.skysrt.com/star-rocks/api/v1/query-service?token=37f749e518af436bbebbe5ad"

    payload = json.dumps({
        "modelId": "lifeAssistantButtonConversion",
        "requireParams": {
            "day": f"{date}"
        }
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    #print(response.text)
    dataJson = json.loads(response.text)
    conn, cur = getConfConnection()
    delsql = f" delete from inter_actify_r_button_number where ref_date= '{date}' "
    cur.execute(delsql)
    conn.commit()
    rowsInt = 0
    for item in dataJson["data"]:
        rowsInt = rowsInt + 1
        sql = "INSERT INTO inter_actify_r_button_number (uv, pv, ref_date, button_id) VALUES (%s, %s, %s, %s)"
        values = (item["uv"], item["pv"], item["day"], item["ask_buttonid"])
        cur.execute(sql, values)
    conn.commit()
    logDetail = f"{date}日-保存按钮点击次数,新增的按钮次数为{rowsInt}"
    print(logDetail)

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

if __name__ == '__main__':
    today = getdate(1)
    getNodeNum(today)
    #getButtonNum(today)

